<template>
  <div class="follow-item">
    <van-button v-if="!isFollow" @click="onFollow" :loading="loading"
      type="info" color="#3296fa" round size="small" icon="plus">关注</van-button>
    <van-button v-else @click="onFollow" :loading="loading" round size="small">已关注</van-button>
  </div>
</template>

<script>
import { getFollows, addFollow, deleteFollow } from '@/api/user'
import { mapState } from 'vuex'

export default {
  name: 'FollowItem',
  components: {},
  props: {
    followId: { type: Number, required: true },
    followName: { type: String, required: true }
  },
  data () {
    return {
      loading: false,
      isFollow: false,
      follows: {}
    }
  },
  computed: {
    ...mapState(['user'])
  },
  watch: {},
  created () {
    if (this.user) {
      this.initFollows()
    }
  },
  mounted () {},
  methods: {
    async initFollows () {
      try {
        this.follows = await getFollows({ userId: this.user.id })
        if (this.followName === 'company') {
          this.follows.company.filter(item => {
            if (item.id === this.followId) {
              this.isFollow = item.isFollow
            }
          })
        } else if (this.followName === 'staff') {
          this.follows.staff.filter(item => {
            if (item.id === this.followId) {
              this.isFollow = item.isFollow
            }
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    async onFollow () {
      try {
        if (!this.user) return this.$router.push('/login')
        this.loading = true
        if (this.followName === 'company') {
          this.follows.company = this.follows.company.map(item => {
            if (item.id === this.followId) {
              item.isFollow = !this.isFollow
            }
            return item
          })
        } else if (this.followName === 'staff') {
          this.follows.staff = this.follows.staff.map(item => {
            if (item.id === this.followId) {
              item.isFollow = !this.isFollow
            }
            return item
          })
        }
        this.isFollow ? await deleteFollow(this.follows) : await addFollow(this.follows)
        this.loading = false
        this.initFollows()
        this.$toast.success(`${this.isFollow ? '取消关注' : '关注'}成功`)
      } catch (error) {
        console.log(error)
        // 无论成功还是失败, 都需要关闭 loading
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.follow-item {
  width: 152px;
  height: 50px;
  .van-button {
    width: 100%;
    height: 100%;
  }
}
</style>
